package com.cxb;

import java.text.SimpleDateFormat;
import java.util.TimeZone;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.provider.ContactsContract.CommonDataKinds.Event;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cxb.manager.CxbEventBus;
import com.cxb.utils.Debug;
import com.cxb.view.DialogCreater;
import com.cxb.view.GpsInfoView;

/**
 * 
 * 描述：GPS测试 陈伟斌 2014-3-5
 */
public class GpsTestActivity extends BaseActivity {

	public boolean bIsFixed = false;
	public long dwTTFFStart = SystemClock.elapsedRealtime();
	private GpsInfoView mGpsInfo;
	private TextView tTTFF = null;
	private TextView info = null;
	private ImageView earth = null;
	private TextView ibReset;
	private Handler mHandler = null;
	private TimeThread dThread = null;
	private View signal_starts;

	private View toolbar;
	GpsResetReceiver gpsResetReceiver;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		this.setContentView(R.layout.setting_gps_test_layout);

		mHandler = new HandlerTime();
		initView();

		UpdatePageGps();
		dThread = new TimeThread();
		dThread.start();

		// CxbEventBus.resgist(CxbEventBus.EVENT_GPS_RESET, this);
		gpsResetReceiver = new GpsResetReceiver();
		this.registerReceiver(gpsResetReceiver, new IntentFilter(
				"EVENT_GPS_RESET"));
	}

	class GpsResetReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Log.i("test", "EVENT_GPS_RESET");
			if (mGpsInfo != null) {
				dwTTFFStart = SystemClock.elapsedRealtime();
				mGpsInfo.reInitGpsView();
			}

		}
	}

	@Override
	protected void onDestroy() {
		this.unregisterReceiver(gpsResetReceiver);
		super.onDestroy();
	}

	@Override
	protected void onStop() {
		// //////////////////////////////////
		dThread.stopThread();
		finish();
		// ///////////////////////////////////
		super.onStop();
	}

	private void initView() {

		tTTFF = (TextView) findViewById(R.id.gps_ttff);
		info = (TextView) findViewById(R.id.gps_info);
		earth = (ImageView) findViewById(R.id.viewEarth);
		toolbar = (View) findViewById(R.id.lly_quick_switch_bar);
		ibReset = (TextView) findViewById(R.id.ib_reset);
		ibReset.setVisibility(View.GONE);
		// Bitmap bitmapEarth = BitmapFactory.decodeResource(getResources(),
		// R.drawable.earth);
		// int nDisplayWidth = ScreenUtil.getScreenWidth(this);
		// int nDisplayHeight = ScreenUtil.getScreenHeight(this);

		mGpsInfo = new GpsInfoView(this);
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				Rect rect = new Rect();
				earth.getGlobalVisibleRect(rect);
				mGpsInfo.MoveEarth(rect.left + 40 , rect.top +40, rect.width()-80 ,
						rect.height()-80);

				Rect toolbarRect = new Rect();
				toolbar.getGlobalVisibleRect(toolbarRect);
				Debug.printf(
						"vita",
						toolbarRect.left + "  " + toolbarRect.top + "  "
								+ toolbarRect.width() + "  "
								+ toolbarRect.height());
				mGpsInfo.MoveSignal(toolbarRect.left , toolbarRect.top ,
						toolbarRect.width(), toolbarRect.height());
				mGpsInfo.SetStarRadius(10);
			}
		}, 300);

		this.addContentView(mGpsInfo, new RelativeLayout.LayoutParams(
				RelativeLayout.LayoutParams.MATCH_PARENT,
				RelativeLayout.LayoutParams.MATCH_PARENT));

		/**
		 * 冷启动
		 */
		ibReset.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				
				DialogCreater dc = new DialogCreater(GpsTestActivity.this);
				final Dialog dialog = dc.getCommonDialog(R.string.prompt, R.string.verify);
				TextView tv_confirm  = (TextView)dc.getView(R.id.tv_confirm);
				TextView tv_cancel  = (TextView)dc.getView(R.id.tv_cancel);
				tv_confirm.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						mGpsInfo.ColdStart();
						dwTTFFStart = SystemClock.elapsedRealtime();
						dialog.dismiss();
					}
				});
				
				tv_cancel.setOnClickListener(new OnClickListener() {
					
					@Override
					public void onClick(View arg0) {
						dialog.dismiss();
					}
				});
//				AlertDialog.Builder builder = new Builder(GpsTestActivity.this);
//				builder.setMessage(R.string.verify);
//				builder.setTitle(R.string.prompt);
//				builder.setPositiveButton(R.string.confirm,
//						new DialogInterface.OnClickListener() {
//
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//								mGpsInfo.ColdStart();
//								dwTTFFStart = SystemClock.elapsedRealtime();
//								dialog.dismiss();
//							}
//						});
//				builder.setNegativeButton(R.string.cancel,
//						new DialogInterface.OnClickListener() {
//
//							@Override
//							public void onClick(DialogInterface dialog,
//									int which) {
//								dialog.dismiss();
//							}
//						});
//				builder.create().show();
				dialog.show();
			}
		});

	}

	// @Override
	// protected void onDestroy() {
	// dThread.stopThread();
	// super.onDestroy();
	// }

	class HandlerTime extends Handler {
		@Override
		public void handleMessage(Message msg) {
			UpdatePageGps();
		}
	};

	public class TimeThread extends Thread {
		private int iCount = 0;
		private boolean bStart = false;

		@Override
		public synchronized void start() {
			bStart = true;
			super.start();
		}

		public void stopThread() {
			bStart = false;
		}

		@Override
		public void run() {
			while (bStart) {
				try {
					sleep(100);
				} catch (Exception e) {
					e.printStackTrace();
				}

				if (iCount++ >= 10) {
					iCount = 0;
					mHandler.sendEmptyMessage(0);
				}
			}
		}
	}

	void UpdatePageGps() {
		Debug.printf("vita", " mGpsInfo.bFixed = " + !mGpsInfo.bFixed
				+ "  !bIsFixed " + !bIsFixed);
		if (!mGpsInfo.bFixed) {
			// if (!bIsFixed) {
			tTTFF.setText("TTFF:"
					+ Long.toString((SystemClock.elapsedRealtime() - dwTTFFStart) / 1000 + 1));
			Debug.printf("vita", "TTFF:" + tTTFF.getText().toString());
			info.setText("123");
			// }
		} else {
			// if (!bIsFixed)
			// bIsFixed = true;
		}

		if (mGpsInfo.gpsStatus != null) {
			SimpleDateFormat date = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
			// date.setTimeZone(TimeZone.getTimeZone("gmt"));
			info.setText(
					String.format(
							"Signal State:%s\r\nLatitude:%C%.06f\r\nLongitude:%C%.06f\r\nUTC:%s\r\nSatellites In View:%d\r\nSatellites In Use:%d\nSpeed:%f km/h\nVDOP:%.02f HDOP:%.02f PDOP:%.02f",
							// (!mGpsInfo.bFixed) ? "Invalid"
							// : (mGpsInfo.nSvInUse > 3) ? "3D" : "2D",
							mGpsInfo.getMode(),
							(mGpsInfo.stLocation.getLatitude() > 0) ? 'N' : 'S',
							(mGpsInfo.stLocation.getLatitude() > 0) ? mGpsInfo.stLocation
									.getLatitude() : -mGpsInfo.stLocation
									.getLatitude(),
							(mGpsInfo.stLocation.getLongitude() > 0) ? 'E'
									: 'W',
							(mGpsInfo.stLocation.getLongitude() > 0) ? mGpsInfo.stLocation
									.getLongitude() : -mGpsInfo.stLocation
									.getLongitude(), date
									.format(mGpsInfo.stLocation.getTime()),
							mGpsInfo.nSvCount, mGpsInfo.nSvInUse,
							mGpsInfo.stLocation.getSpeed() * 3.6f, mGpsInfo
							.getVDOP(), mGpsInfo.getHDOP(), mGpsInfo.getPDOP()));
		} else {
			info.setText("Signal State:Invalid\r\nLatitude:0.000000\r\nLongitude:0.000000\r\nUTC:00/00/2000 00:00:00\r\nSatellites In View:0\r\nSatellites In Use:0\nSpeed:0.000000 km/h");
		}

	}

	int clickCount = 0;

	@Override
	public boolean onTouchEvent(MotionEvent event) {

		if (event.getAction() == MotionEvent.ACTION_DOWN) {
			float x = event.getX();
			float y = event.getY();
			Rect rect = new Rect();
			earth.getGlobalVisibleRect(rect);
			if (rect.contains((int) x, (int) y)) {
				clickCount++;
				if (clickCount >= 6) {
					ibReset.setVisibility(View.VISIBLE);
				}
			} else {
				clickCount = 0;
			}
			Log.i("test", "clickCount=" + clickCount);
		}
		return super.onTouchEvent(event);
	}

}
